package cn.com.yang.egg;

import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.lang.reflect.Field;

/**
 * @Desc<子类调用祖父类方法>
 * @Author 杨亿金
 * @Date 2021/1/18 14:38
 * @CopyRight
 * @Version
 */
public class EggInvokeGrandFather {
    class GrandFather{
        void thinking(){
            System.out.println("I am grandFather");
        }
    }
    class Father extends GrandFather{
        void thinking() {
            System.out.println("I am father");
        }
    }
    class Son extends Father{
        void thinking(){
            try {
                MethodType mt = MethodType.methodType(void.class);
                Field lookupImpl = MethodHandles.Lookup.class.getDeclaredField("IMPL_LOOKUP");
                lookupImpl.setAccessible(true);
                MethodHandle mh = ((MethodHandles.Lookup)lookupImpl.get(null)).
                        findSpecial(GrandFather.class,"thinking",mt,GrandFather.class);
                mh.invoke(this);
            }catch (Throwable e){

            }
        }
        //JDK7 update9之前 打印是I am grandFather update10之后是 I am father
        /*void thinking2(){
            try {
                MethodType mt = MethodType.methodType(void.class);
                MethodHandle mh=lookup().findSpecial(GrandFather.class,"thinking",mt,getClass());
                mh.invoke(this);
            }catch (Throwable e){

            }
        }*/
    }

    public static void main(String[] args) {
        (new EggInvokeGrandFather().new Son()).thinking();
    }
}
